//
//  SCCertificateUploadSecStyleCell.m
//  Shuaiche
//
//  Created by xiangtao on 2024/3/25.
//  Copyright © 2024 ShuaiChe. All rights reserved.
//

#import "SCCertificateUploadSecStyleCell.h"
#import "SCCarImageEditViewController.h"
#import "SCCarAddImageItemCell.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "TZImagePickerController.h"
#import "TZImageManager.h"
#import "MBProgressHUD+Add.h"
#import "UIImageView+SCwebImage.h"

static CGFloat const origin_x = 14.0f;
static CGFloat const origin_y = 14.0f;
static CGFloat const bottom = 10.0f;
static CGFloat const cell_space = 12.0f;
const NSInteger numbersOfRow = 4;

@interface SCCertificateUploadSecStyleCell ()<UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, TZImagePickerControllerDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate,SCCarAddImageItemCellDelegate>
{
    __weak UIViewController            *viewController_;
    CGFloat cellHeight;
    NSArray *preShows_;
    ImageUploadCertificateType uploadCertificateType_;
}
@property(strong, nonatomic) UICollectionView *collectionView;
@end

static NSString *const cellId = @"cellId";

@implementation SCCertificateUploadSecStyleCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier viewController:(UIViewController *)viewController preShows:(NSArray *)preShows type:(ImageUploadCertificateType)uploadCertificateType maxPics:(NSInteger)maxPics {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        viewController_ = viewController;
        preShows_ = preShows;
        uploadCertificateType_ = uploadCertificateType;
        _maxPics = maxPics;
        
        [self createSingleImageModel];
        
        cellHeight = (kSCScreenWidth-cell_space*3-origin_x*2)/numbersOfRow;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, origin_y, kSCScreenWidth, [self resizeHieight]) collectionViewLayout:[self collectionViewLayout]];
        _collectionView.scrollEnabled = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [self.contentView addSubview:_collectionView];
        if (@available(iOS 11.0 , *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        [self configureCollectionView];
        
        [self.collectionView reloadData];
    }
    return self;
}

- (void)configureCollectionView{
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.contentInset = UIEdgeInsetsMake(0, origin_x, origin_x, 0);
    self.collectionView.alwaysBounceVertical = YES;
    [self.collectionView registerNib:[UINib nibWithNibName:@"SCCarAddImageItemCell" bundle:nil] forCellWithReuseIdentifier:@"SCCarAddImageItemCell"];
}

- (void)createSingleImageModel {
    SCCarAddImageModel *model = [[SCCarAddImageModel alloc] init];
    model.isShowAll = YES;
    NSMutableArray *imagesArray = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *showImagesArray = [NSMutableArray arrayWithCapacity:0];
    for (NSDictionary *dic in preShows_) {
        NSString *title = [dic objectForKey:@"title" defaultValue:nil];
        NSString *description = [dic objectForKey:@"description" defaultValue:nil];
        if ([title isEqualToString:@"CERT_PIC"]) {
            if (uploadCertificateType_ == ImageUploadCertificateTypeCarCertificate && [description isEqualToString:@"CAR_REG_BOOK"]) {
                SCCarAddImageItemModel *itemModel = [[SCCarAddImageItemModel alloc] init];
                itemModel.title = @"CERT_PIC";
                itemModel.carDescription = @"CAR_REG_BOOK";
                [itemModel addSelecteImage:nil withPath:dic[kPicUrl]];
                [imagesArray addObject:itemModel];
                [showImagesArray addObject:itemModel];
            } else if (uploadCertificateType_ == ImageUploadCertificateTypeOther && [description isEqualToString:@"OTHER_CERT"]) {
                SCCarAddImageItemModel *itemModel = [[SCCarAddImageItemModel alloc] init];
                itemModel.title = @"CERT_PIC";
                itemModel.carDescription = @"OTHER_CERT";
                [itemModel addSelecteImage:nil withPath:dic[kPicUrl]];
                [imagesArray addObject:itemModel];
                [showImagesArray addObject:itemModel];
            }
        }
    }
    [showImagesArray addObject:[SCCarAddImageItemModel addModel]];
    model.imagesArray = imagesArray;
    model.showImagesArray = showImagesArray;
    _currentModel = model;
    [self.dataSource addObject:model];
}

#pragma mark - UICollectionViewdelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SCCarAddImageModel *model = self.dataSource[section];
    if (model.isShowAll) {
        return MIN(model.showImagesArray.count,self.maxPics);
    }
    return 0;
}

- (UICollectionViewLayout *)collectionViewLayout {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(floorf((kSCScreenWidth - 52) /numbersOfRow), floorf((kSCScreenWidth - 52) /numbersOfRow));
    flowLayout.minimumLineSpacing = 8;
    return flowLayout;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataSource.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
    footer.backgroundColor = SC_Color_Separator;
    return footer;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    SCCarAddImageModel *model = self.dataSource[section];
    if (model.isShowAll) {
        return UIEdgeInsetsMake(0, 0, 0, 10);
    }
    return UIEdgeInsetsMake(0, 0, 0, 10);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeZero;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SCCarAddImageItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SCCarAddImageItemCell" forIndexPath:indexPath];
    cell.positionName.hidden = YES;
    cell.delegate = self;
    SCCarAddImageModel *model = self.dataSource[indexPath.section];
    SCCarAddImageItemModel *itemModel = model.showImagesArray[indexPath.row];
    if (indexPath.row == 0) {
        cell.mainPicTag.hidden = itemModel.isAddButton;
    } else {
        cell.mainPicTag.hidden = YES;
    }
    cell.deleteBtn.hidden = itemModel.isAddButton;
    if (itemModel.imageUrlPath) {
        [cell.imageView sc_setImageWithPath:itemModel.imageUrlPath];
    } else {
        cell.imageView.image = itemModel.image;
    }
    NSLog(@"cell刷新了");
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SCCarAddImageModel *model = self.dataSource[indexPath.section];
    SCCarAddImageItemModel *itemModel = model.showImagesArray[indexPath.row];
    if (itemModel.isAddButton) {
//        self.currentModel = model;
        [self showActionSheet];
    } else {
        SCCarImageEditViewController *edit = [[SCCarImageEditViewController alloc] init];
        if (!itemModel.image) {
            SCCarAddImageItemCell *cell = (SCCarAddImageItemCell *)[collectionView cellForItemAtIndexPath:indexPath];
            itemModel.image = cell.imageView.image;
        }
        if (!itemModel.image) {
            [MBProgressHUD showError:@"暂未获取到图片"];
            return;
        }
        edit.editImage = itemModel.image;
        [viewController_.navigationController pushViewController:edit animated:YES];
        edit.reloadBlock = ^(UIImage *image,BOOL isProcess) {
            if (isProcess) {
                itemModel.imageUrlPath = nil;
                itemModel.asset = nil;
            }
            itemModel.image = image;
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
        };
        
        edit.deleteBlock = ^{
            [model.showImagesArray removeObject:itemModel];
            [model.imagesArray removeObject:itemModel];
            model.selectNormalCount --;
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
        };
        
        edit.toMainPicBlock = ^{
            [model.showImagesArray removeObject:itemModel];
            [model.showImagesArray insertObject:itemModel atIndex:0];
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
            
            [model.imagesArray removeObject:itemModel];
            [model.imagesArray insertObject:itemModel atIndex:0];
        };
    }
}

#pragma mark - SCCarAddImageItemCellDelegate
- (void)SCCarAddImageItemCellDidDeletePic:(SCCarAddImageItemCell *)cell
{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    SCCarAddImageModel *model = self.dataSource[indexPath.section];
    SCCarAddImageItemModel *itemModel = model.showImagesArray[indexPath.row];
    [model.showImagesArray removeObject:itemModel];
    [model.imagesArray removeObject:itemModel];
    model.selectNormalCount --;
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
    
    [self reloadView];
}

#pragma mark -- Photo Fetch

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<UIImagePickerControllerInfoKey, id> *)editingInfo {
    [picker dismissViewControllerAnimated:YES completion:nil];
    SCCarAddImageItemModel *addModel = self.currentModel.showImagesArray.lastObject;
    if (addModel.isAddButton) {
        [self.currentModel.showImagesArray removeLastObject];
    }
    SCCarAddImageItemModel *model = [[SCCarAddImageItemModel alloc] init];
    model.title = @"CERT_PIC";
    model.carDescription = uploadCertificateType_ == ImageUploadCertificateTypeCarCertificate ? @"CAR_REG_BOOK":(uploadCertificateType_ == ImageUploadCertificateTypeOther ? @"OTHER_CERT":@"");
    model.image = image;
    model.fillImage = YES;
    self.currentModel.selectNormalCount++;
    [self.currentModel.showImagesArray addObject:model];
    [self.currentModel.showImagesArray addObject:addModel];
    [self.currentModel.imagesArray addObject:model];
    [self.collectionView reloadData];
    
    [self reloadView];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    SCCarAddImageItemModel *addModel = self.currentModel.showImagesArray.lastObject;
    if (addModel.isAddButton) {
        [self.currentModel.showImagesArray removeObject:addModel];
    }
    for (NSInteger i = 0; i < photos.count; i++) {
        UIImage *image = photos[i];
        PHAsset *asset = assets[i];
        SCCarAddImageItemModel *model = [[SCCarAddImageItemModel alloc] init];
        model.title = @"CERT_PIC";
        model.carDescription = uploadCertificateType_ == ImageUploadCertificateTypeCarCertificate ? @"CAR_REG_BOOK":(uploadCertificateType_ == ImageUploadCertificateTypeOther ? @"OTHER_CERT":@"");
        [model addSelecteImage:image withPath:nil];
        model.asset = asset;
        [self.currentModel.showImagesArray addObject:model];
        [self.currentModel.imagesArray addObject:model];
        self.currentModel.selectNormalCount++;
    }
    [self.currentModel.showImagesArray addObject:addModel];
    [self.collectionView reloadData];
    NSMutableArray *mAssetsAry = [NSMutableArray arrayWithArray:self.currentModel.selectedAssets];
    [mAssetsAry addObjectsFromArray:assets];
    self.currentModel.selectedAssets = mAssetsAry;
    
    [self reloadView];
}

- (void)showActionSheet {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showCamera];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showPhotoAlume];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [viewController_ presentViewController:alert animated:YES completion:nil];
}

- (void)showPhotoAlume {
    [self presetnPhotoAlume:(self.maxPics+1) - self.currentModel.showImagesArray.count];
}

- (void)showCamera {
    [viewController_ dismissViewControllerAnimated:NO completion:nil];
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        // picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [viewController_ presentViewController:picker animated:YES completion:nil];
    }
}

- (void)presetnPhotoAlume:(NSInteger)count {
    
    TZImagePickerController *imagePickController = [[TZImagePickerController alloc] initWithMaxImagesCount:count delegate:self];
//    imagePickController.minImagesCount = 1;
    //是否 在相册中显示拍照按钮
    imagePickController.allowTakePicture = NO;
    //是否可以选择显示原图
    imagePickController.allowPickingOriginalPhoto = YES;
    //是否 在相册中可以选择视频
    imagePickController.allowPickingVideo = NO;
//    imagePickController.showSelectBtn = YES;
    imagePickController.naviBgColor = [UIColor whiteColor];
    imagePickController.naviTitleColor = [UIColor blackColor];
    imagePickController.barItemTextColor = [UIColor blackColor];
    imagePickController.statusBarStyle = UIStatusBarStyleDefault;
    //    imagePickController.selectedAssets = _currentModel.selectedAssets;
    imagePickController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickController.navLeftBarButtonSettingBlock = ^(UIButton *lefyButton){
        [lefyButton setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    };
    [viewController_ presentViewController:imagePickController animated:YES completion:nil];
}

#pragma mark - resizeHieight
- (CGFloat)resizeHieight
{
    NSInteger count = self.currentModel.showImagesArray.count;

    CGFloat height = origin_y+((count-1)/numbersOfRow+1)*cellHeight+((count-1)/numbersOfRow*cell_space)+bottom+10;
    
    return height;
}

- (void)reloadView {
    _collectionView.frame = CGRectMake(0, origin_y, kSCScreenWidth, [self resizeHieight]);
    if (self.reloadHeight) {
        self.reloadHeight();
    }
}

@end
